package aes

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
)

//参考 openssl_encrypt("27891", "aes-256-cbc", "mmc00000000000ZzzZ00000000000mmc", 0, "0000000000000000");
func Ase256CbcEncode(plaintext string, key string, iv string, blockSize int) string {
	bKey := []byte(key)
	bIV := []byte(iv)
	bPlaintext := PKCS5Padding([]byte(plaintext), blockSize, len(plaintext))
	block, _ := aes.NewCipher(bKey)
	ciphertext := make([]byte, len(bPlaintext))
	mode := cipher.NewCBCEncrypter(block, bIV)
	mode.CryptBlocks(ciphertext, bPlaintext)
	return base64.StdEncoding.EncodeToString(ciphertext)
}
//参考 openssl_decrypt("mnugCJOoFHnoHHvOjkhBaA==", "aes-256-cbc", "mmc00000000000ZzzZ00000000000mmc", 0,"0000000000000000");
func Ase256CbcDecode(cipherText string, key string, iv string) string {
	originData , _ := base64.StdEncoding.DecodeString( cipherText )
	ivV := []byte(iv)
	keyByteString := key
	cipherBlock, err := aes.NewCipher([]byte(keyByteString))
	if err != nil{
		//fmt.Println(err)
		return ""
	}
	cipher.NewCBCDecrypter(cipherBlock, ivV).CryptBlocks(originData, originData)
	return string(PKCS5UnPadding(originData))
}

func PKCS5Padding(ciphertext []byte, blockSize int, after int) []byte {
	padding := (blockSize - len(ciphertext)%blockSize)
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}
func PKCS5UnPadding(src []byte) []byte {
	length := len(src)
	unpadding := int(src[length-1])
	if length - unpadding < 0 {
		return []byte("")
	}
	return src[:(length - unpadding)]
}